<?php
/**
 * Created by PhpStorm.
 * User: MI
 * Date: 2019/1/21
 * Time: 14:10
 */

namespace App\Http\Controllers\Api;


use App\Http\Controllers\Controller;
use App\Http\Requests\RoleRequest;
use App\Http\Resources\RoleResource;
use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RoleController extends Controller
{
    public function index(Request $request){
        $keyword = $request->get('keyword', null);
        $models = Role::query()->when($keyword, function ($query) use ($keyword) {
            return $query->where('name', 'like', '%' . $keyword . '%');
        })
            ->where('guard_name','admin')->paginate();
        return RoleResource::collection($models);
    }

    /**
     * @param RoleRequest $request
     * @return RoleResource|\Illuminate\Http\JsonResponse
     */
    public function store(RoleRequest $request)
    {
        $name = $request->get('name');
        $permissions = $request->get('permissions');
        DB::beginTransaction();
        try {
            $role = Role::create(['name'=>$name,'guard_name'=>'admin']);
//            $role->givePermissionTo($permissions);
            $role->permissions()->sync($permissions);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return response()->json(['type' => 'error', 'message' => $exception->getMessage()], 462);
        }
        return new RoleResource($role);
    }

    /**
     * @param $id
     * @return RoleResource
     */
    public function show($id)
    {
        $model = $this->findModel($id);
        return new RoleResource($model);
    }

    /**
     * @param RoleRequest $request
     * @param $id
     * @return RoleResource|\Illuminate\Http\JsonResponse
     */
    public function update(RoleRequest $request, $id)
    {
        $name = $request->get('name');
        $permissions = $request->get('permissions');
        DB::beginTransaction();
        try {
            $model = $this->findModel($id);
            $model->name = $name;
            if (!$model->save()) {
                throw new \Exception('保存失败', 500);
            }
            $model->permissions()->sync($permissions);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            dd($exception);
            return response()->json(['type' => 'error', 'message' => $exception->getMessage()], 462);
        }
        return new RoleResource($model);
    }


    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model
     */
    public function findModel($id)
    {
        $model = Role::query()->findOrFail($id);
        return $model;
    }

}
